package com.xoa.service.knowledge.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.knowledge.KnowledgeColumnMapper;
import com.xoa.dao.knowledge.KnowledgeDocfileMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.common.SysPara;
import com.xoa.model.knowledge.KnowledgeColumn;
import com.xoa.model.knowledge.KnowledgeDocfile;
import com.xoa.model.users.Users;
import com.xoa.service.knowledge.FileManageService;
import com.xoa.service.knowledge.util.KnowledgeUtil;
import com.xoa.util.CookiesUtil;
import com.xoa.util.LimsJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class FileManageServiceImpl implements FileManageService {

    @Autowired
    private KnowledgeDocfileMapper knowledgeDocfileMapper;

    @Autowired
    private KnowledgeColumnMapper knowledgeColumnMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    private KnowledgeUtil knowUtil = null;
    /**
     *
     * @作者 李卫卫
     * @创建日期 12:17 2020/9/14
     * @类介绍 编辑文档
     * @参数
     * @return limsJson
     */
    @Override
    public LimsJson updateBySelective(KnowledgeDocfile record) {
        LimsJson limsJson = new LimsJson(1, "err");
        if (record != null) {
            try {
                int count = knowledgeDocfileMapper.updateByPrimaryKeySelective(record);
                if(count>0){
                    limsJson.setMsg("编辑成功");
                    limsJson.setFlag(0);
                    limsJson.setCode(0);
                }else {
                    limsJson.setMsg("编辑失败");
                    limsJson.setFlag(1);
                }
            } catch (Exception e) {
                limsJson.setFlag(1);
                limsJson.setMsg("编辑失败，程序出现问题，请联系开发人员");
                e.printStackTrace();
            }
        }else {
            limsJson.setMsg("请提交要编辑的文档");
            limsJson.setFlag(1);
        }
        return limsJson;
    }


    /**
     *
     * @作者 李卫卫
     * @创建日期 12:32 2020/9/14
     * @类介绍 查看文档
     * @参数
     * @return limsJson
     */
    @Override
    public LimsJson selectByDocfileId(Integer docfileId) {
        LimsJson limsJson = new LimsJson(1,"err");
        try {
            KnowledgeDocfile knowledgeDocfile = knowledgeDocfileMapper.selectByDocfileId(docfileId);
            if(knowledgeDocfile!=null){
                limsJson.setObject(knowledgeDocfile);
                limsJson.setMsg("查看成功");
                limsJson.setFlag(0);
                limsJson.setCode(0);
            }else {
                limsJson.setMsg("查看失败");
                limsJson.setFlag(1);
            }
        }catch (Exception e){
            limsJson.setFlag(1);
            limsJson.setMsg("查看失败，程序出现问题，请联系开发人员");
            e.printStackTrace();
        }
        return limsJson;
    }


    /**
     * @Author: ZhuYize
     * @Date: 2020/9/14 19:21
     * @Description: 获取栏目类型下的文档
     * @param: columnIds
     * @return: LimsJson
     */
    @Override
    public LimsJson getFiles(String columnIds, Integer page, Integer limit) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        limsJson.setFlag(1);
        // 封装查询参数和分页数据
        Map<String, Object> param = new HashMap<>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        param.put("page", pageParams);
        if(!StringUtils.checkNull(columnIds)){
            List<KnowledgeColumn> list = knowledgeColumnMapper.findChildByCId(columnIds);
            String ids = "";
            if(list.size()>0){
                for (KnowledgeColumn k: list) {
                    ids += k.getColumnId() + ",";
                }
            }
            String[] split = ids.split(",");
            param.put("columnIds", split);
        }
        // 通过栏目类型id串查询数据并分页
        List<KnowledgeDocfile> knowledgeDocfileList = knowledgeDocfileMapper.selectByColumnIdsAndPaging(param);
        Map<String, Object> param2 = new HashMap<>();
        if(!StringUtils.checkNull(columnIds)){
            String[] ids = columnIds.split(",");
            param2.put("columnIds", ids);
        }
        // 通过栏目类型id串查询数据并分页
        List<KnowledgeDocfile> knowlgeDoileLi = knowledgeDocfileMapper.selectByColumnIdsAndPaging(param2); //产品分页涉及到参数类型为数组，getTotle会无效，只能不要分页再查一次
        limsJson.setCode(0);
        limsJson.setFlag(0);
        limsJson.setCount(pageParams.getTotal());
        if (knowledgeDocfileList.size() > 0) {
            // 封装栏目类别数据

            for (KnowledgeDocfile docfile : knowledgeDocfileList) {
                docfile.setDownloadAddress("http://localhost:8082/knowledge/download?key="+docfile.getDownloadAddress());
                String data = "";
                List<String> dataList = new ArrayList<>();
                String[] str = (docfile.getColumnId()).split(",");
                // 通过子节点查询该子节点之上的多有节点
                String columnName = "";
                for (String s : str) {
                    if(!StringUtils.checkNull(s)){
                        KnowledgeColumn knowledgeColumn;
                        List<String> textList = new ArrayList<>();
                        boolean flag = true;
                        knowledgeColumn = knowledgeColumnMapper.selectByPrimaryKey(Integer.valueOf(s));
                        if(knowledgeColumn!=null){
                            columnName+=knowledgeColumn.getColumnName()+",";
                        }
//                        while (flag) {
//                            if (knowledgeColumn.getParentColumnId() != 0) {
//                                knowledgeColumn = knowledgeColumnMapper.selectByPrimaryKey(knowledgeColumn.getParentColumnId());
//                                textList.add(knowledgeColumn.getColumnName());
//                            } else {
//                                flag = false;
//                            }
//                        }
//                        for (int i = textList.size() - 1; i >= 0; i--) {
//                            if (i != 0) {
//                                text += textList.get(i) + " --> ";
//                            } else {
//                                text += textList.get(i);
//                            }
//                        }
//                        dataList.add(text);
                    }

                }
                if(columnName.endsWith(",")){
                    columnName = columnName.substring(0,columnName.length()-1);
                }
                docfile.setColumnName(columnName);
//                for (int j = 0, g = 1; j < dataList.size(); j++, g++) {
//                    if (j != 0) {
//                        data += g + "、" + dataList.get(j) + "\n";
//                    } else {
//                        data += g + "、" + dataList.get(j);
//                    }
//                }
              //  docfile.setColumnName(data);
                //上传人
                String createUserId = docfile.getCreateUserId();
                if(createUserId != null){
                    Users usersByuserId = usersMapper.findUsersByuserId(createUserId);
                    if(usersByuserId !=null && usersByuserId.getUserName() != null){
                        docfile.setCreateUserId(usersByuserId.getUserName());
                    }
                }
                //文件等级
                if(docfile.getDocfileClass() != null){
                    SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_DOCFILE_CLASS", docfile.getDocfileClass());
                    if(sysCode !=null && sysCode.getCodeName()!=null)
                    docfile.setDocfileClass(sysCode.getCodeName());

                }
            }
            limsJson.setCount(knowlgeDoileLi.size());
            limsJson.setData(knowledgeDocfileList);
            limsJson.setMsg("查询成功！");
        } else {
            limsJson.setMsg("无数据");
        }
        return limsJson;
    }


    /**
     * @Author: ZhuYize
     * @Date: 2020/9/15 15:17
     * @Description: 删除文档
     * @param: delFile 文档id串
     * @return: LimsJson
     */
    @Override
    public LimsJson deleteFile(String docfileIds) {
        LimsJson limsJson = new LimsJson<>(1, "删除失败");
        limsJson.setCode(1);
        if (docfileIds != null && !(("").equals(docfileIds))) {
            String[] ids = docfileIds.split(",");
            try {
                // 批量删除
                int result = knowledgeDocfileMapper.deleteByDocfileIds(ids);
                if (result > 0) {
                    limsJson.setCode(0);
                    limsJson.setFlag(0);
                    limsJson.setMsg("删除成功");
                }
            } catch (Exception e) {
                limsJson.setMsg("删除失败，文档可能关联其他数据");
                e.printStackTrace();
            }
        } else {
            limsJson.setMsg("删除失败，程序出现错误，请联系开发人员");
        }
        return limsJson;
    }


    /**
     * @Author: ZhuYize
     * @Date: 2020/9/15 16:16
     * @Description: 新增文档
     * @param: request 请求数据
     * @param: knowledgeDocfile 添加的数据
     * @return: LimsJson
     */
    @Override
    public LimsJson insertFile(HttpServletRequest request, KnowledgeDocfile knowledgeDocfile) {
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            if(StringUtils.checkNull(knowledgeDocfile.getDownloadAddress())){
                if(knowUtil==null){
                    knowUtil = new KnowledgeUtil();
                }
                knowledgeDocfile.setDownloadAddress(knowUtil.GetRandomString(30));
            }else{
                knowledgeDocfile.setDownloadAddress(knowledgeDocfile.getDownloadAddress().split("=")[1]);
            }
            Map param = new HashMap();
            KnowledgeDocfile kd = new KnowledgeDocfile();
            kd.setDownloadAddress(knowledgeDocfile.getDownloadAddress());
            param.put("knowledgeDocfile",kd);
            List<KnowledgeDocfile> kdList = knowledgeDocfileMapper.search(param);
            if(kdList!=null&&kdList.size()>0){
                limsJson.setFlag(1);
                limsJson.setMsg("添加失败,下载地址已重复，请刷新下载地址重试");
            }else{
                Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
                knowledgeDocfile.setCreateUserId(user.getUserId());
                String columnIds = knowledgeDocfile.getColumnId();
                if(!StringUtils.checkNull(columnIds)){
                    String[] columnIdArr = columnIds.split(",");
                    String cIds = ",";
                    for(String cid : columnIdArr){
                        if(!StringUtils.checkNull(cid)){
                            cIds+=cid+",";
                        }
                    }
                    knowledgeDocfile.setColumnId(cIds);
                    knowledgeDocfile.setCreateTime(new Date());
                    int count = knowledgeDocfileMapper.insertSelective(knowledgeDocfile);
                    if (count > 0) {
                        limsJson.setFlag(0);
                        limsJson.setCode(0);
                        limsJson.setMsg("添加成功");
                    } else {
                        limsJson.setFlag(1);
                        limsJson.setMsg("添加失败");
                    }
                }else{
                    limsJson.setMsg("添加失败，请选择知识栏目");
                }
            }
        } catch (Exception e) {
            limsJson.setFlag(1);
            limsJson.setMsg("添加失败，程序出现问题，请联系管理员");
            e.printStackTrace();
        }
        return limsJson;
    }

    /**
     * 条件查询文档
     * @param request
     * @param knowledgeDocfile
     * @param page
     * @param limit
     * @return
     */
    @Override
    public LimsJson serchFile(HttpServletRequest request, KnowledgeDocfile knowledgeDocfile,Integer page,Integer limit){
        LimsJson limsJson = new LimsJson(1, "err");
        try {
            Map map = new HashMap();
            if(knowledgeDocfile!=null){
                PageParams pageParams = new PageParams();
                if(page!=null&&limit!=null){
                    if(page!=null&&limit!=null){ //开启分页
                        pageParams.setUseFlag(true);
                        pageParams.setPage(page);
                        pageParams.setPageSize(limit);
                        map.put("page", pageParams);
                    }
                }
                map.put("knowledgeDocfile",knowledgeDocfile);
                List<KnowledgeDocfile> fileList = knowledgeDocfileMapper.search(map);
                if (fileList.size() > 0) {
                    limsJson.setFlag(0);
                    limsJson.setData(fileList);
                    limsJson.setCode(0);
                    limsJson.setCount(pageParams.getTotal());
                    limsJson.setMsg("查询成功");
                } else {
                    limsJson.setFlag(1);
                    limsJson.setMsg("添加失败");
                }
            }else{
                limsJson.setMsg("请输入查询条件");
            }
        } catch (Exception e) {
            limsJson.setFlag(1);
            limsJson.setMsg("查询失败，程序出现问题，请联系管理员");
            e.printStackTrace();
        }
        return limsJson;
    }

    @Override
    public LimsJson generStr(HttpServletRequest request){
        LimsJson limsJson = new LimsJson(1, "err");
        if(knowUtil==null){
            knowUtil = new KnowledgeUtil();
        }
        String str = knowUtil.GetRandomString(30); //生成30位随机数
        limsJson.setObj("http://localhost:8082/download?key="+str);
        return limsJson;
    }

}